

#import "WeiboHeader.h"
#import "UIView+RectSize.h"

#import "mcf.h"
#import "UIViewAdditions.h"


@implementation WeiboUrlShortenResult
@synthesize url_long;
@synthesize url_short;
@synthesize result;

-(id) initWithUrlLong:(NSString*)url_longx urlShort:(NSString*)url_shortx result:(BOOL)resultx {
    self = [super init];
    if (self) {
        self.url_long = url_longx;
        self.url_short = url_shortx;
        self.result = resultx;
    }
    return self;
}

-(void) dealloc {
    YRelease(url_long)
    YRelease(url_short)
    [super dealloc];
}
@end

@implementation WeiboUrlClicksResult
@synthesize url_long;
@synthesize url_short;
@synthesize clicks;

-(id) initWithUrlLong:(NSString*)url_longx urlShort:(NSString*)url_shortx clicks:(int)clicksx {
    self = [super init];
    if (self) {
        self.url_long = url_longx;
        self.url_short = url_shortx;
        self.clicks = clicksx;
    }
    return self;
}

-(void) dealloc {
    YRelease(url_long)
    YRelease(url_short)
    [super dealloc];
}
@end








// 全部保持 空实现，否则 编译 不通过

@implementation WeiboBase
@synthesize backupGetFriendshipIdx=_backupGetFriendshipIdx;
@synthesize backupFollowIdx=_backupFollowIdx;
@synthesize backupGetCommentsIdx=_backupGetCommentsIdx;
@synthesize backupCommentIdx=_backupCommentIdx;
@synthesize backupCommentContent=_backupCommentContent;
@synthesize backupGetFriendsNextCursor=_backupGetFriendsNextCursor;
@synthesize backupgetFriendsReqnum=_backupgetFriendsReqnum;

//@synthesize theDelegate = _theDelegate;
-(id) onetimeDelegate // private
{
    id temp = _theDelegate;
    _theDelegate = nil; // 只有一次回调机会
    return temp;//theDelegate
}
-(void) setOnetimeDelegate:(id)theDelegate {
    @synchronized(self){
        if (theDelegate!=nil) assert(_theDelegate==nil);
        _theDelegate = theDelegate;
    }
}

+(BOOL) isAuthorized {
    return [[[[self alloc] init] autorelease] isAuthorized];
}

-(id<WeiboCommitDelegate>) getWeiboCommitDelegate { return self.onetimeDelegate; }
-(id<WeiboGetFriendshipDelegate>) getWeiboGetFriendshipDelegate { return self.onetimeDelegate; }
-(id<WeiboFollowDelegate>) getWeiboFollowDelegate { return self.onetimeDelegate; }
-(id<WeiboGetUserInfoDelegate>) getWeiboGetUserInfoDelegate { return self.onetimeDelegate; }
-(id<WeiboShortUrlClicksDelegate>) getWeiboShortUrlClicksDelegate { return self.onetimeDelegate; }
-(id<WeiboShortUrlClicksArrayDelegate>) getWeiboShortUrlClicksArrayDelegate { return self.onetimeDelegate; }
-(id<WeiboShortUrlShortenDelegate>) getWeiboShortUrlShortenDelegate { return self.onetimeDelegate; }
-(id<WeiboShortUrlShortenArrayDelegate>) getWeiboShortUrlShortenArrayDelegate { return self.onetimeDelegate; }
-(id<WeiboShortUrlShareCountsDelegate>) getWeiboShortUrlShareCountsDelegate { return self.onetimeDelegate; }
-(id<WeiboShortUrlShareStatusDelegate>) getWeiboShortUrlShareStatusDelegate { return self.onetimeDelegate; }
-(id<WeiboShortUrlCommentCountsDelegate>) getWeiboShortUrlCommentCountsDelegate { return self.onetimeDelegate; }
-(id<WeiboShortUrlCommentCommentsDelegate>) getWeiboShortUrlCommentCommentsDelegate { return self.onetimeDelegate; }
-(id<WeiboSearchDelegate>) getWeiboSearchDelegate { return self.onetimeDelegate; }
-(id<WeiboCommentsShowDelegate>) getWeiboCommentsShowDelegate { return self.onetimeDelegate; }
-(id<WeiboCommentCreateDelegate>) getWeiboCommentCreateDelegate { return self.onetimeDelegate; }
-(id<WeiboNodeShowDelegate>) getWeiboNodeShowDelegate { return self.onetimeDelegate; }
-(id<WeiboFriendsDelegate>) getWeiboFriendsDelegate { return self.onetimeDelegate; }

//assert(self.authDelegate == nil); 有点特殊，不管他。
@synthesize authDelegateBackup;
@synthesize  authDelegate=_authDelegate; // 有点特殊，不管TA -- 需要的时候需要 单独建一个实例，避免。WeiboBase。。xxx

-(id) init {
    self = [super init];
    if (self) {
        _theDelegate = nil;
    }
    return self;
}

-(void) dealloc
{
    [_userName release];
    [_domainUrl release];
    [_userNode release];
    [_backupCommentContent release];
    [super dealloc];
}

-(NSString*) rootNick
{
    return [WeiboBase rootNick];
}
+(NSString*) rootNick
{
    NSString* ret = @"@Yuike优客";//[Parameters valueforKey:ParemetersKey_YUIKE_WEIBO_NICK_ROOT ];
    return [ret strip]; // 不能有空格。
}



-(NSString*) nick { 
    NSString* ret = [[self _protected_nick] strip];
    return [ret stringByAppendingString:@" "]; // 必须补充一个 空格
}

-(BOOL)havUserNameDomain
{
    return _userName!=nil && [_userName compare:@""] != 0 &&
            _domainUrl!=nil && [_domainUrl compare:@""] != 0;
}

-(void) setDelegateNilAll {
    _authDelegate = nil;
    _theDelegate = nil;
}
-(void) cancelAll {  assert(false); 
}
-(BOOL) isinWorking {
    if (_theDelegate != nil) return true;
    return false;
}



-(NSArray*)emotions {
    assert(false);
}
-(NSArray*)urlStringsforCookies {  assert(false); 
    return [NSArray array];
}



// ===================================================
-(NSString*) myDomainUrl
{
    if (_domainUrl == nil)
        [self loadCurrentUserInfo];
    return _domainUrl;
}
-(void) setMyDomainUrl:(NSString *)domainUrl_
{
    if (_domainUrl) [_domainUrl release];
    if (domainUrl_ != nil)
        _domainUrl = [[NSString alloc] initWithString:domainUrl_];
    else
        _domainUrl = nil;
    [self saveCurrentUserInfo];
}
-(NSString*) myUserName
{
    if (_userName == nil)
        [self loadCurrentUserInfo];
    return _userName;
}
-(void) setMyUserName:(NSString *)userName_
{
    if (_userName) [_userName release];
    if (userName_ != nil)
        _userName = [[NSString alloc] initWithString:userName_];
    else
        _userName = nil;
    [self saveCurrentUserInfo];
}
-(WeiboUserNode*) myUserNode // 后来的版本才加的，这个函数还存在问题，没调试过。
{
    if (_userNode == nil)
        [self loadCurrentUserInfo];
    return _userNode;
}
-(void) setMyUserNode:(WeiboUserNode *)myUserNode_ {
    if (_userNode) [_userNode release];
    if (myUserNode_ != nil) {
        _userNode = [myUserNode_ retain];
    } else {
        _userNode = nil;
    }
    [self saveCurrentUserInfo];//WeiboUserNode
}
-(NSString*) myDomainfromUrl {
    NSString* temp = self.myDomainUrl;
    if (!temp || temp.length <= 0) {
        return nil;
    }
    NSArray* array = [temp split:@"/"];
    if (array.count <= 0) {
        return nil;
    }
    return [array objectAtIndex:[array count]-1];
}


-(void) loadCurrentUserInfo
{
    NSString* key = [[[self class] description] stringByAppendingString:@".userName"];
    if (_userName) [_userName release];
    _userName = [[[NSUserDefaults standardUserDefaults] valueForKey: key] retain];
    
    key = [[[self class] description] stringByAppendingString:@".domainUrl"];
    if (_domainUrl) [_domainUrl release];
    _domainUrl = [[[NSUserDefaults standardUserDefaults] valueForKey: key] retain];
    
    key = [[[self class] description] stringByAppendingString:@".userNode"];
    if (_userNode) [_userNode release];
    _userNode = [[[NSUserDefaults standardUserDefaults] valueForKey: key] retain];
}
-(void) saveCurrentUserInfo
{
    NSString* key = [[[self class] description] stringByAppendingString:@".userName"];
    [[NSUserDefaults standardUserDefaults] setValue:_userName forKey: key];
    
    key = [[[self class] description] stringByAppendingString:@".domainUrl"];
    [[NSUserDefaults standardUserDefaults] setValue:_domainUrl forKey: key];
    
    key = [[[self class] description] stringByAppendingString:@".userNode"];
    [[NSUserDefaults standardUserDefaults] setValue:_userNode forKey: key];
	[[NSUserDefaults standardUserDefaults] synchronize];
}


-(BOOL) isOpened
{return true;
    NSString* key = [[[self class] description] stringByAppendingString:@".isOpened"];
    NSString* value = [[NSUserDefaults standardUserDefaults] valueForKey: key];
    return value.intValue != 0;
}
-(void) setOpened:(BOOL)opened
{
    NSString* key = [[[self class] description] stringByAppendingString:@".isOpened"];
    [[NSUserDefaults standardUserDefaults] setValue:(opened?@"1":@"0") forKey: key];
	[[NSUserDefaults standardUserDefaults] synchronize];
}


-(void) signOutx
{
    self.myUserName = nil;
    self.myDomainUrl = nil;
    self.myUserNode = nil;
    [self saveCurrentUserInfo];
    [self _protected_signOut];
}



// 子类必须 实现的有 －＝＝＝＝：

-(void) auth:(id<WeiboAuthDelegate>)delegate{assert(false);
}
-(void) commit:(id<WeiboCommitDelegate>)delegate content:(NSString *)content image:(UIImage*)image{assert(false);
}
-(void) _protected_signOut {  assert(false);  }
-(NSString*) _protected_nick {  assert(false);return @""; }
-(void) getFriendship:(id<WeiboGetFriendshipDelegate>)delegate idx:(long long)idx{assert(false);
}
-(void) follow:(id<WeiboFollowDelegate>)delegate idx:(long long)idx{assert(false);
}
-(void) getUserInfo:(id<WeiboGetUserInfoDelegate>)delegate{assert(false);
}
-(void) search:(id<WeiboSearchDelegate>)delegate_ qvalue:(NSString*)qvalue{assert(false);
}
-(void) getCommentsTENC:(id<WeiboCommentsShowDelegate>)delegate_ 
                 rootid:(long long)rootid
               pageflag:(int)pageflag
               pagetime:(long long)pagetime
                 reqnum:(int)reqnum
              twitterid:(long long)twitterid {assert(false);}
-(void) getCommentsSINAv1:(id<WeiboCommentsShowDelegate>)delegate_ 
                      idx:(long long)idx
                    count:(int)count
                     page:(int)page {assert(false);}
-(void) getCommentsSINAv2:(id<WeiboCommentsShowDelegate>)delegate_ 
                      idx:(long long)idx 
                 since_id:(long long)since_id
                   max_id:(long long)max_id
                    count:(int)count 
                     page:(int)page {assert(false);}
-(void) addShare:(id<WeiboCommitDelegate>)delegate_ content:(NSString*)content 
           title:(NSString*)title url:(NSString*)url summary:(NSString*)summary
        imageurl:(NSString*)imageurl {assert(false);
}
-(void) comment:(id<WeiboCommentCreateDelegate>)delegate_ idx:(long long)idx  comment:(NSString*)comment {assert(false);
}
-(void) getNode:(id<WeiboNodeShowDelegate>)delegate_ idx:(long long)idx   {assert(false);
}

-(void) getFriends:(id<WeiboFriendsDelegate>)delegate_ page:(int)page reqnum:(int)reqnum {assert(false);
}
-(int) getFriendsFirstIntvalue {
    assert(false);
}
-(int) getFriendsMaxReqnum {
    assert(false);
}












//http://count.chanet.com.cn/click.cgi?a=400395&d=222185&u=yuikemall_iPad%2520Simulator_iPhone%2520OS_4%252E3%252E2_%2528null%2529&e=&url=http%253A%252F%252Fwww%252Elamiu%252Ecom%252Fgoods_4834%252Ehtml
//http://count.chanet.com.cn/click.cgi?a=400395&d=222185&u=yuikemall_iPad%20Simulator_iPhone%20OS_4%2E3%2E2_%28null%29&e=&url=http%3A%2F%2Fwww%2Elamiu%2Ecom%2Fgoods_4834%2Ehtml
-(NSString*) title{  assert(false); return nil; }
-(NSString*) cpsUrlTrans:(NSString*)cpsUrl { return cpsUrl; };

-(UIImage*) theIcon32x32{ assert(false);  return nil; }
-(UIImage*) theIcon48x48{  assert(false); return nil; }
-(int) theSnsId{ assert(false);  return 0; }

-(BOOL) isAuthorized{ assert(false);  return NO; }
-(void) reloadAuthInfo { assert(false); } // 多个实例，照成的数据没有得到及时更新...所以需要有一个 强制重新加载

// 子类必须调用 基类 === 如果使用的话 -- 目的是 给 auth web view 加一个进度指示圈。。。  // 子类必须调用 基类
#define HUD_ID 1998 // 添加 MBProgressHUD的个数 和 移除的一样多，保证平衡。
#define FAILED_ID 1999
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    [self.authDelegate authCallbackCurrentRequest:webView.request];
    return  true;
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [self.authDelegate authCallbackCurrentRequest:webView.request];
    //DebugLog(@"WeiboAuth: %@", [[webView.request URL] absoluteString]);
    [[webView viewWithTag:FAILED_ID] removeFromSuperview];
    
    MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView: webView];
    hud.mode = MBProgressHUDModeIndeterminateGray;
    hud.notBackground = true;
    [hud autorelease];
    [webView addSubview: hud];
    [hud show: TRUE];
    hud.tag = HUD_ID;
    
    hud = nil; // 仅仅最后一个显示
    NSArray* subviews = webView.subviews;
    for (int i = 0; i < subviews.count; i++) {
        UIView* view = (UIView*) [subviews objectAtIndex:i];
        if ([view isKindOfClass:MBProgressHUD.class]) {
            if (hud != nil)
                hud.hidden = YES;
            hud = (MBProgressHUD*) view;
        }
    }
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self.authDelegate authCallbackCurrentRequest:webView.request];
    
    MBProgressHUD* hud = (MBProgressHUD*)[webView viewWithTag:HUD_ID];
    [hud removeFromSuperview]; // HUD_ID
    //[hud hide: YES];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [self.authDelegate authCallbackCurrentRequest:webView.request];
    
    MBProgressHUD* hud = (MBProgressHUD*)[webView viewWithTag:HUD_ID];
    [hud removeFromSuperview]; // HUD_ID
    //[hud hide: YES];
    
    
    if (error && error.userInfo) {
        NSString* _temp = [error.userInfo valueForKey:@"NSErrorFailingURLStringKey"];
        if (_temp && [_temp startswith:@"http://localhost/"])
            return;
        _temp = [error.userInfo valueForKey:@"NSErrorFailingURLKey"];
        if (_temp && [_temp startswith:@"http://localhost/"])
            return;
    }
    
    
 
    UIImageView* view = [[UIImageView alloc] init]; // webview_crashed.jpg
    view.image = [UIImage imageNamed:@"webview_crashed.jpg"];
    view.frame = CGRectMake(0, 0, view.image.size.width, view.image.size.height);
    [view autorelease];
    view.center = [webView boundsCenter];
    view.alpha = 0.1;
    //[webView addSubview:view];
    
    // 喔唷，网页加载失败啦！
    UILabel* label = [[UILabel alloc] initWithFrame:view.frame];
    label.text = @"郁闷~网页加载不成功";
    label.alpha = 0.1;
    [[webView viewWithTag:FAILED_ID] removeFromSuperview];
    [webView addSubview:label];
    [label autorelease];
    label.tag = FAILED_ID;
    
    label.textAlignment = UITextAlignmentCenter;
    
    CGRect frame = label.frame;
    frame.origin.x -= 100;
    frame.size.width += 200;
    frame.origin.y -= 50;
    frame.size.height += 100;
    label.frame = frame;
    
    label.center = webView.boundsCenter; // 居中。。。
    label.top -= 24;
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration: 1.0];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    view.alpha = 1.0;
    label.alpha = 1.0;
    [UIView commitAnimations];
}
@end

